//
//  剑指Offer 22. 链表中倒数第k个节点.swift
//  Top600
//
//  Created by rjb on 2021/8/10.
//

import Foundation
class SolutionOffer22 {
    func getKthFromEnd(_ head: ListNode?, _ k: Int) -> ListNode? {
        // 采用快慢指针
        var slow = head
        var fast = head
        var k = k
        while fast != nil {
            if k == 0 {
                slow = slow?.next
            } else {
                k -= 1
            }
            fast = fast?.next
        }
        return slow
    }
    static func test() {
        let solution = SolutionOffer22()
        let node1 = ListNode(1)
        let node2 = ListNode(2)
        let node3 = ListNode(3)
        let node4 =  ListNode(4)
        let node5 =  ListNode(5)
        node1.next = node2
        node2.next = node3
        node3.next = node4
        node4.next = node5
        
        let result =  solution.getKthFromEnd(node1, 2)
        print(result)
    }
}
